<xsl:stylesheet version='1.0'
  xmlns:xsl='http://www.w3.org/1999/XSL/Transform'
  xmlns:xlink="http://www.w3.org/1999/xlink"
  xmlns:db="http://docbook.org/ns/docbook"
  xmlns:pbs="http://schema.pbs.gov.au"
  xmlns:rwt="http://schema.pbs.gov.au/RWT/"
  xmlns:dr='http://schema.pbs.gov.au/DR/'>

  <xsl:import href='common.xsl'/>

  <db:article>
    <db:info>
      <db:title>Extract Drug File</db:title>

      <db:copyright>
        <db:year>2013</db:year>
        <db:year>2012</db:year>
        <db:year>2011</db:year>
        <db:year>2009</db:year>
        <db:holder>Commonwealth of Australia</db:holder>
      </db:copyright>

      <db:legalnotice>
        <db:para>This software is copyrighted by the Commonwealth of Australia ("The Commonwealth").  The following terms apply to all files associated with the software unless explicitly disclaimed in individual files.</db:para>
        <db:para>Permission is hereby granted to use, copy, modify, distribute, and license this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. No written agreement, license, or royalty fee is required for any of the authorized uses. Modifications to this software may be copyrighted by their authors and need not follow the licensing terms described here, provided that the new terms are clearly indicated on the first page of each file where they apply.</db:para>
        <db:para>IN NO EVENT SHALL THE COMMONWEALTH OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</db:para>
        <db:para>THE COMMONWEALTH SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE COMMONWEALTH HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.</db:para>
      </db:legalnotice>

      <db:author>
        <db:personname>Steve Ball</db:personname>
        <db:email>Steve.Ball@health.gov.au</db:email>
        <db:affiliation>
          <db:orgname>Department of Health and Ageing</db:orgname>
          <db:orgdiv>PharmBiz</db:orgdiv>
        </db:affiliation>
      </db:author>

      <db:revhistory>
        <db:revision>
          <db:revnumber>2.22</db:revnumber>
          <db:date>2013-10-31</db:date>
          <db:authorinitials>SRB</db:authorinitials>
          <db:revremark>Use common template for translating characters to ASCII.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.21.2</db:revnumber>
          <db:date>2013-08-30</db:date>
          <db:authorinitials>SRB</db:authorinitials>
          <db:revremark>Further fix to brand-substitution when TPP is deleted.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.21.1</db:revnumber>
          <db:date>2013-08-08</db:date>
          <db:authorinitials>SRB</db:authorinitials>
          <db:revremark>Fixed brand-substitution when TPP is deleted.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.21</db:revnumber>
          <db:date>2013-07-22</db:date>
          <db:authorinitials>SRB</db:authorinitials>
          <db:revremark>Change sorting of TPPs to make infusible entries more stable.  Remove rwt:prescriber-instruction content from notes.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.20.3</db:revnumber>
          <db:date>2013-04-29</db:date>
          <db:authorinitials>SRB</db:authorinitials>
          <db:revremark>Update documentation.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.20.2</db:revnumber>
          <db:date>2013-03-05</db:date>
          <db:authorinitials>SRB</db:authorinitials>
          <db:revremark>Fix MRVSN in no-premium pricing model.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.20.1</db:revnumber>
          <db:date>2013-01-08</db:date>
          <db:authorinitials>SRB</db:authorinitials>
          <db:revremark>Fix unstable bioequivalence indicator.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.20</db:revnumber>
          <db:date>2012-12-19</db:date>
          <db:authorinitials>DMM</db:authorinitials>
          <db:revremark>Added parameter option to choose to not truncate fields.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.19.2</db:revnumber>
          <db:date>2012-12-18</db:date>
          <db:authorinitials>SRB</db:authorinitials>
          <db:revremark>Fixed brand substitution indicator</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.19.1</db:revnumber>
          <db:date>2012-11-22</db:date>
          <db:authorinitials>DMM</db:authorinitials>
          <db:revremark>Fixed translation of #233 character from y to e</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.19</db:revnumber>
          <db:date>2012-11-08</db:date>
          <db:authorinitials>DMM</db:authorinitials>
          <db:revremark>Added sorting of results.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.18.3</db:revnumber>
          <db:date>2012-11-07</db:date>
          <db:authorinitials>DMM</db:authorinitials>
          <db:revremark>Added documentation.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.18.2</db:revnumber>
          <db:date>2012-10-23</db:date>
          <db:authorinitials>SRB</db:authorinitials>
          <db:revremark>Fixed error in determining bioequivalence indicator. When determining DD fee code also consider whether fee is defined in dispensing rule. Moved default dispensing rule to common module.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.17</db:revnumber>
          <db:date>2012-09-17</db:date>
          <db:authorinitials>SRB</db:authorinitials>
          <db:revremark>Fixed error in determining manufacturer DPMQ.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.16.1</db:revnumber>
          <db:date>2012-09-10</db:date>
          <db:authorinitials>DMM</db:authorinitials>
          <db:revremark>Fixed errors in determining bioequivalence flag.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.16</db:revnumber>
          <db:date>2012-08-22</db:date>
          <db:authorinitials>SRB</db:authorinitials>
          <db:revremark>Changed determination of bioequivalence flag for LBSGs.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.15</db:revnumber>
          <db:date>2012-08-15</db:date>
          <db:authorinitials>DMM</db:authorinitials>
          <db:revremark>Added in parameter and code for testing purposes to insert a markup code where one isn't able to be determined from the data.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.14</db:revnumber>
          <db:date>2012-08-14</db:date>
          <db:authorinitials>DMM</db:authorinitials>
          <db:revremark>Fixed bug for finding notes where administrative-advice-reference children of restrictions weren't considered.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.13.2</db:revnumber>
          <db:date>2012-07-18</db:date>
          <db:authorinitials>SRB</db:authorinitials>
          <db:revremark>Performance optimisation.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.13.1</db:revnumber>
          <db:date>2012-05-30</db:date>
          <db:authorinitials>SRB</db:authorinitials>
          <db:revremark>Check MPP for dangerous drug group membership.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.13</db:revnumber>
          <db:date>2012-05-16</db:date>
          <db:authorinitials>SRB</db:authorinitials>
          <db:revremark>Use both QNames and URIs for dispensing rules. Use named templates to allow customisation.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.12</db:revnumber>
          <db:date>2011-12-01</db:date>
          <db:authorinitials>BD</db:authorinitials>
          <db:revremark>Fix the Ready-prepared Therapeutic Group Manufacturer's dpmq value</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.11</db:revnumber>
          <db:date>2011-11-29</db:date>
          <db:authorinitials>BD</db:authorinitials>
          <db:revremark>Allocate bio-equivalence brand substitution group values (a or b)</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.10</db:revnumber>
          <db:date>2011-11-24</db:date>
          <db:authorinitials>BD</db:authorinitials>
          <db:revremark>Fix note inclusion plus exclude notes with non-numeric codes (e.g. cto and scm)</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.9</db:revnumber>
          <db:date>2011-11-24</db:date>
          <db:authorinitials>BD</db:authorinitials>
          <db:revremark>Fixed caution identification</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.8</db:revnumber>
          <db:date>2011-11-22</db:date>
          <db:authorinitials>BD</db:authorinitials>
          <db:revremark>Assign ATC type value based on postion in classification</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.7</db:revnumber>
          <db:date>2011-11-22</db:date>
          <db:authorinitials>DMM</db:authorinitials>
          <db:revremark>Fixed incorrect truncation of drug-name to be 80 characters instead 150. Added new dispensing rule variable for special access items and changed determination of the dr.this variable for TY and TZ program codes.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.6</db:revnumber>
          <db:date>2011-11-18</db:date>
          <db:authorinitials>BD</db:authorinitials>
          <db:revremark>Fixes for infusible drugs and caution flags</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.5</db:revnumber>
          <db:date>2011-11-14</db:date>
          <db:authorinitials>DMM</db:authorinitials>
          <db:revremark>Modified keys to address performance issues</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.4</db:revnumber>
          <db:date>2011-10-31</db:date>
          <db:authorinitials>DMM</db:authorinitials>
          <db:revremark>Fee type code now correctly handles infusibles.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.3</db:revnumber>
          <db:date>2011-10-21</db:date>
          <db:authorinitials>DMM</db:authorinitials>
          <db:revremark>Updated for PBS XML v2.6.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.2.2</db:revnumber>
          <db:date>2011-10-11</db:date>
          <db:authorinitials>SRB</db:authorinitials>
          <db:revremark>Fixed MRVSN for infusible items.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.2.1</db:revnumber>
          <db:date>2011-10-06</db:date>
          <db:authorinitials>SRB</db:authorinitials>
          <db:revremark>Fixed markup code.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.2</db:revnumber>
          <db:date>2011-09-27</db:date>
          <db:authorinitials>SRB</db:authorinitials>
          <db:revremark>Changed URIs for dispensing rules.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.1</db:revnumber>
          <db:date>2011-06-22</db:date>
          <db:authorinitials>SRB</db:authorinitials>
          <db:revremark>Added support for infusibles.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.0.1</db:revnumber>
          <db:date>2011-06-14</db:date>
          <db:authorinitials>SRB</db:authorinitials>
          <db:revremark>Fixed blank dollar values. Fixed note flag.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.0</db:revnumber>
          <db:date>2011-02-15</db:date>
          <db:authorinitials>SRB</db:authorinitials>
          <db:revremark>Updated for PBS XML Schema v2.4.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>1.1</db:revnumber>
          <db:date>2009-09-25</db:date>
          <db:authorinitials>SRB</db:authorinitials>
          <db:revremark>Updating for new pricing model.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>1.0</db:revnumber>
          <db:date>2009-08-27</db:date>
          <db:authorinitials>SRB</db:authorinitials>
          <db:revremark>Initial version.</db:revremark>
        </db:revision>
      </db:revhistory>
    </db:info>

    <db:para>This XSL stylesheet produces the Drug extract file (<db:filename>Drug yyyymmdd.txt</db:filename>) from a PBS XML document. Only ready prepared and infusible items are extracted.</db:para>
    <db:para>The source document must be a PBS XML document.</db:para>
    <db:para>The result document is a text file.</db:para>
    <db:para>The default field delimeter in this file is the exclamation mark (!).</db:para>
    <db:table>
      <db:tgroup cols="4" align="left" colsep="1" rowsep="1">
        <db:colspec colnum="3" align="right"/>
        <db:thead>
          <db:row>
            <db:entry>Field Name</db:entry>
            <db:entry>Format</db:entry>
            <db:entry>Maximum Length</db:entry>
            <db:entry>Description</db:entry>
          </db:row>
        </db:thead>
        <db:tbody>
          <db:row>
            <db:entry>Program Code</db:entry>
            <db:entry>Character</db:entry>
            <db:entry>2</db:entry>
            <db:entry>two character alphabetic, see separate table below</db:entry>
          </db:row>
          <db:row>
            <db:entry>ATC Code</db:entry>
            <db:entry>Character</db:entry>
            <db:entry>8</db:entry>
            <db:entry>refer to file ATC yyyymmdd.txt</db:entry>
          </db:row>
          <db:row>
            <db:entry>ATC Type</db:entry>
            <db:entry>Character</db:entry>
            <db:entry>1</db:entry>
            <db:entry>
              <db:para>one character alphabetic, one value:</db:para>
              <db:simplelist>
                <db:member>P - primary reference</db:member>
              </db:simplelist>
            </db:entry>
          </db:row>
          <db:row>
            <db:entry>ATC Print Option</db:entry>
            <db:entry>Character</db:entry>
            <db:entry>1</db:entry>
            <db:entry>
              <db:para>determines how THIS drug item listed under THIS ATC code is printed in the Schedule of Pharmaceutical Benefits - one character numeric, one value:</db:para>
              <db:simplelist>
                <db:member>1 - print full entry ONLY</db:member>
              </db:simplelist></db:entry>
          </db:row>
          <db:row>
            <db:entry>PBS Code</db:entry>
            <db:entry>Character</db:entry>
            <db:entry>5</db:entry>
            <db:entry>Five or six character in format (n)nnnna; for allocations of PBS code blocks see separate table below</db:entry>
          </db:row>
          <db:row>
            <db:entry>Restriction Flag</db:entry>
            <db:entry>Character</db:entry>
            <db:entry>1</db:entry>
            <db:entry>
              <db:para>one character alphabetic, three possible values:</db:para>
              <db:simplelist>
                <db:member>U - unrestricted</db:member>
                <db:member>R - restricted benefit</db:member>
                <db:member>A - authority required</db:member>
              </db:simplelist>
            </db:entry>
          </db:row>
          <db:row>
            <db:entry>Caution Flag</db:entry>
            <db:entry>Character</db:entry>
            <db:entry>1</db:entry>
            <db:entry>one character alphabetic, C if Caution attached, otherwise blank</db:entry>
          </db:row>
          <db:row>
            <db:entry>Note Flag</db:entry>
            <db:entry>Character</db:entry>
            <db:entry>1</db:entry>
            <db:entry>one character alphabetic, N if Note(s) attached,otherwise blank</db:entry>
          </db:row>
          <db:row>
            <db:entry>Maximum Quantity (Maximum Amount for infusible items)</db:entry>
            <db:entry>Character</db:entry>
            <db:entry>5</db:entry>
            <db:entry>the maximum quantity (units-of-use) published in the Schedule</db:entry>
          </db:row>
          <db:row>
            <db:entry>Number of Repeats</db:entry>
            <db:entry>Character</db:entry>
            <db:entry>2</db:entry>
            <db:entry>the maximum number of repeats published in the Schedule</db:entry>
          </db:row>
          <db:row>
            <db:entry>Manufacturer's Code</db:entry>
            <db:entry>Character</db:entry>
            <db:entry>2</db:entry>
            <db:entry>two character alphabetic, refer to file Mnfr yyyymmdd.txt</db:entry>
          </db:row>
          <db:row>
            <db:entry>Pack Size</db:entry>
            <db:entry>Character</db:entry>
            <db:entry>4</db:entry>
            <db:entry>the quantity contained in the manufacturer's pack</db:entry>
          </db:row>
          <db:row>
            <db:entry>Mark-up Code</db:entry>
            <db:entry>Character</db:entry>
            <db:entry>1</db:entry>
            <db:entry>
              <db:para>one character alphabetic (current rates in file Fees yyyymmdd.txt), four values:</db:para>
              <db:simplelist>
                <db:member>A - no mark-up (section 100 drug types)</db:member>
                <db:member>B - 50% (not currently in use)</db:member>
                <db:member>C - standard six-tier ready-prepared mark-up; the price to pharmacist for maximum quantity determines which tier applies</db:member>
                <db:member>D - HSD four-tier ready-prepared mark-up; the price to pharmacist for maximum quantity determines which tier applies</db:member>
                <db:member>E - one-tier ready-prepared mark-up</db:member>
              </db:simplelist>
            </db:entry>
          </db:row>
          <db:row>
            <db:entry>Dispense Fee Type Code</db:entry>
            <db:entry>Character</db:entry>
            <db:entry>2</db:entry>
            <db:entry>
              <db:para>two characters alphabetic (current rates in file Fees yyyymmdd.txt), four values:</db:para>
              <db:simplelist>
                <db:member>NF - no fee (section 100 drug types)</db:member>
                <db:member>RP - ready-prepared</db:member>
                <db:member>EP - extemporaneously-prepared</db:member>
                <db:member>EW - extemporaneously-prepared + purified water</db:member>
              </db:simplelist>
            </db:entry>
          </db:row>
          <db:row>
            <db:entry>Dangerous Drug Fee Code</db:entry>
            <db:entry>Character</db:entry>
            <db:entry>2</db:entry>
            <db:entry>DD (current rate in file Fees yyyymmdd.txt) if  dangerous drug fee payable, otherwise blank</db:entry>
          </db:row>
          <db:row>
            <db:entry>Brand Premium</db:entry>
            <db:entry>Character</db:entry>
            <db:entry>10</db:entry>
            <db:entry></db:entry>
          </db:row>
          <db:row>
            <db:entry>Therapeutic Group Premium</db:entry>
            <db:entry>Character</db:entry>
            <db:entry>10</db:entry>
            <db:entry>This is the Therapeutic Group Premium (or Special Patient Contribution)</db:entry>
          </db:row>
          <db:row>
            <db:entry>Commonwealth Price to Pharmacist</db:entry>
            <db:entry>Character</db:entry>
            <db:entry>10</db:entry>
            <db:entry>Reimbursement price-to-pharmacist for manufacturer's pack. For S100 programs this value is the price ex-manufacturer.</db:entry>
          </db:row>
          <db:row>
            <db:entry>Commonwealth Dispensed Price for Maximum Quantity (Maximum Amount for infusible items)</db:entry>
            <db:entry>Character</db:entry>
            <db:entry>10</db:entry>
            <db:entry></db:entry>
          </db:row>
          <db:row>
            <db:entry>Therapeutic Group Manufacturer's Price to Pharmacist</db:entry>
            <db:entry>Character</db:entry>
            <db:entry>10</db:entry>
            <db:entry>This is the Therapeutic Group Manufacturer's Price to Pharmacist (or Special Patient Contribution Manufacturer's Price to Pharmacist) (for manufacturer's pack). For S100 programs this value is the price ex-manufacturer.</db:entry>
          </db:row>
          <db:row>
            <db:entry>Therapeutic Group Manufacturer's Dispensed Price for Maximum Quantity</db:entry>
            <db:entry>Character</db:entry>
            <db:entry>10</db:entry>
            <db:entry>This is the Therapeutic Group Manufacturer's Dispensed Price for Maximum Quantity (or Special Patient Contribution Manufacturer's Dispensed Price for Maximum Quantity) (for manufacturer's pack).</db:entry>
          </db:row>
          <db:row>
            <db:entry>Manufacturer's Price to Pharmacist </db:entry>
            <db:entry>Character</db:entry>
            <db:entry>10</db:entry>
            <db:entry>For manufacturer's pack. For S100 programs this value is the price ex-manufacturer.</db:entry>
          </db:row>
          <db:row>
            <db:entry>Manufacturer's Dispensed Price for Maximum Quantity (Maximum Amount for infusible items</db:entry>
            <db:entry>Character</db:entry>
            <db:entry>10</db:entry>
            <db:entry></db:entry>
          </db:row>
          <db:row>
            <db:entry>Maximum Recordable Value for Safety Net</db:entry>
            <db:entry>Character</db:entry>
            <db:entry>10</db:entry>
            <db:entry>Maximum Recordable Value for Safety Net</db:entry>
          </db:row>
          <db:row>
            <db:entry>Bioequivalence Indicator</db:entry>
            <db:entry>Character</db:entry>
            <db:entry>1</db:entry>
            <db:entry>Bioequivalence Indicator</db:entry>
          </db:row>
          <db:row>
            <db:entry>Brand Name</db:entry>
            <db:entry>Character</db:entry>
            <db:entry>45</db:entry>
            <db:entry>MAY be truncated at 45 characters</db:entry>
          </db:row>
          <db:row>
            <db:entry>Drug (MP) Name</db:entry>
            <db:entry>Character</db:entry>
            <db:entry>80</db:entry>
            <db:entry>MAY be truncated at 80 characters</db:entry>
          </db:row>
          <db:row>
            <db:entry>AMT MPP preferred term</db:entry>
            <db:entry>Character</db:entry>
            <db:entry>150</db:entry>
            <db:entry>MAY be truncated at 150 characters</db:entry>
          </db:row>
        </db:tbody>
      </db:tgroup>
    </db:table>
  </db:article>

  <xsl:output method='text'/>

  <db:param>
    <db:refpurpose>Header row</db:refpurpose>
    <db:para>Whether to include a header row. Often useful for debugging purposes.</db:para>
  </db:param>
  <xsl:param name='include-header' select='0'/>

  <db:param>
    <db:refpurpose>Delimiter</db:refpurpose>
    <db:para>The character to use to separate fields.</db:para>
  </db:param>
  <xsl:param name='delimiter' select='"!"'/>

  <db:param>
    <db:refpurpose>QNames</db:refpurpose>
    <db:para>Whether to use QNames or expanded URIs.</db:para>
  </db:param>
  <xsl:param name='qnames' select='true()'/>
  
  <db:param>
    <db:refpurpose>Testing</db:refpurpose>
    <db:para>Indicates testing mode. Currently this inserts a markup code where one can not be determined from the data</db:para>
  </db:param>
  <xsl:param name='testing-mode' select='false()'/>

  <db:param>
    <db:refpurpose>Truncate</db:refpurpose>
    <db:para>Indicates whether or not to truncate fields to fit the maximum length. Default is true (truncate fields).</db:para>
  </db:param>
  <xsl:param name='truncate' select='true()'/>

  <xsl:key name='tpp'
    match='/pbs:root/pbs:drugs-list/pbs:mp/pbs:mpp/pbs:tpp'
    use='concat("#", @xml:id)'/>

  <xsl:key name='mpp'
    match='/pbs:root/pbs:drugs-list/pbs:mp/pbs:mpp'
    use='concat("#", @xml:id)'/>

  <xsl:key name='organisation'
    match='/pbs:root/pbs:organisations-list/pbs:organisation'
    use='concat("#", @xml:id)'/>

  <xsl:key name='group'
    match='/pbs:root/pbs:groups-list/pbs:group'
    use='concat("#", @xml:id)'/>
  <xsl:key name="members"
    match="pbs:member-of[not(ancestor::pbs:previous)]"
    use="@xlink:href"/>
    
  <xsl:key name='markup-band'
    match='/pbs:root/pbs:schedule/pbs:listings-list/pbs:dispensing-rules-list/pbs:dispensing-rule/pbs:markups-list/pbs:markup-band'
    use='concat("#", @xml:id)'/>

  <xsl:key name='fee-definition'
    match='/pbs:root/pbs:schedule/pbs:listings-list/pbs:dispensing-rules-list/pbs:dispensing-rule/pbs:fees-list/pbs:fee-definition'
    use='concat("#", @xml:id)'/>

  <xsl:key name='restrictions'
    match='/pbs:root/rwt:restrictions-list/*'
    use='concat("#", @xml:id)'/>

  <db:template name='root'>
    <db:refpurpose>Check Document Version</db:refpurpose>
    <db:para>Make sure that the source document uses the correct version of the PBS XML Schema.</db:para>
  </db:template>
  <xsl:template match='/'>
    <xsl:variable name='major' select='substring-before(/*/@version, ".")'/>

    <xsl:choose>
      <xsl:when test='$major >= 2'>
        <xsl:if test='$include-header != 0'>
          <xsl:text>Drug Type</xsl:text>
          <xsl:value-of select='$delimiter'/>
          <xsl:text>ATC</xsl:text>
          <xsl:value-of select='$delimiter'/>
          <xsl:text>ATC type</xsl:text>
          <xsl:value-of select='$delimiter'/>
          <xsl:text>Print option</xsl:text>
          <xsl:value-of select='$delimiter'/>
          <xsl:text>Item Code</xsl:text>
          <xsl:value-of select='$delimiter'/>
          <xsl:text>Restr. Flag</xsl:text>
          <xsl:value-of select='$delimiter'/>
          <xsl:text>Caution</xsl:text>
          <xsl:value-of select='$delimiter'/>
          <xsl:text>Note</xsl:text>
          <xsl:value-of select='$delimiter'/>
          <xsl:text>MQ</xsl:text>
          <xsl:value-of select='$delimiter'/>
          <xsl:text>Rpts</xsl:text>
          <xsl:value-of select='$delimiter'/>
          <xsl:text>Manu. Code</xsl:text>
          <xsl:value-of select='$delimiter'/>
          <xsl:text>Pk Sz</xsl:text>
          <xsl:value-of select='$delimiter'/>
          <xsl:text>Mrkup</xsl:text>
          <xsl:value-of select='$delimiter'/>
          <xsl:text>Fee Code</xsl:text>
          <xsl:value-of select='$delimiter'/>
          <xsl:text>DD</xsl:text>
          <xsl:value-of select='$delimiter'/>
          <xsl:text>BP</xsl:text>
          <xsl:value-of select='$delimiter'/>
          <xsl:text>TGP</xsl:text>
          <xsl:value-of select='$delimiter'/>
          <xsl:text>Comm P2P</xsl:text>
          <xsl:value-of select='$delimiter'/>
          <xsl:text>Comm DPMQ</xsl:text>
          <xsl:value-of select='$delimiter'/>
          <xsl:text>TG Man P2P</xsl:text>
          <xsl:value-of select='$delimiter'/>
          <xsl:text>TG Man DPMQ</xsl:text>
          <xsl:value-of select='$delimiter'/>
          <xsl:text>Man P2P</xsl:text>
          <xsl:value-of select='$delimiter'/>
          <xsl:text>Man DPMQ</xsl:text>
          <xsl:value-of select='$delimiter'/>
          <xsl:text>MRVSN</xsl:text>
          <xsl:value-of select='$delimiter'/>
          <xsl:text>Bioequiv</xsl:text>
          <xsl:value-of select='$delimiter'/>
          <xsl:text>Brand Name</xsl:text>
          <xsl:value-of select='$delimiter'/>
          <xsl:text>Drug Name</xsl:text>
          <xsl:value-of select='$delimiter'/>
          <xsl:text>Form &amp; Strength&#xa;</xsl:text>
        </xsl:if>
        <xsl:apply-templates select='/pbs:root/pbs:schedule/pbs:listings-list/pbs:prescribing-rule[pbs:ready-prepared|pbs:infusible]'>
          <xsl:sort select='pbs:code'/>
        </xsl:apply-templates>
      </xsl:when>
      <xsl:otherwise>
        <xsl:message terminate='yes'>This stylesheet is designed to operate upon a Schedule XML document that conforms to version 2.0 (or later) of the PBS XML Schema.  See http://xml.pbs.gov.au/ for more information on the PBS XML Schema, and for a version of this XSL stylesheet that operates on documents that conform to an earlier version of the schema.</xsl:message>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

  <xsl:template match='pbs:prescribing-rule'>
    <xsl:if test='pbs:ready-prepared and not(pbs:ready-prepared/pbs:pricing/pbs:prices/pbs:tpp-reference)'>
      <xsl:message>Prescribing rule (ready-prepared) "<xsl:value-of select='pbs:code'/>" has no TPPs</xsl:message>
    </xsl:if>
    <xsl:if test='pbs:infusible and not(pbs:infusible/pbs:pricing/pbs:reimbursement/pbs:prices/pbs:tpp-list/pbs:tpp-reference)'>
      <xsl:message>Prescribing rule (infusible) "<xsl:value-of select='pbs:code'/>" has no TPPs</xsl:message>
    </xsl:if>
    
    <xsl:variable name='pr' select='.'/>
    
    <xsl:for-each select='*/pbs:classification/pbs:ATC'>
      <xsl:sort select='.'/>
      <xsl:apply-templates select='$pr/pbs:ready-prepared/pbs:pricing/pbs:prices/pbs:tpp-reference |
                                            $pr/pbs:infusible/pbs:pricing/pbs:reimbursement/pbs:prices/pbs:tpp-list/pbs:tpp-reference'>
        <xsl:with-param name='pr' select='$pr'/>
        <xsl:with-param name='atc' select='.'/>
        <xsl:sort select='../pbs:vial-content'/>
        <xsl:sort select='key("organisation", key("tpp", @xlink:href)/pbs:organisation-reference/@xlink:href)/pbs:code'/>
        <xsl:sort select='key("tpp", @xlink:href)/db:title'/>
      </xsl:apply-templates>
    </xsl:for-each>
  </xsl:template>

  <xsl:template match='pbs:tpp-reference'>
    <xsl:param name='pr' select='/..'/>
    <xsl:param name='atc' select='/..'/>

    <xsl:variable name='tpp' select='key("tpp", @xlink:href)'/>

    <xsl:choose>
      <xsl:when test='$tpp'>
        <xsl:apply-templates select='$tpp'>
          <xsl:with-param name='pr' select='$pr'/>
          <xsl:with-param name='pricing' select='ancestor::pbs:prices[1]'/>
          <xsl:with-param name='tpp-ref' select='.'/>
          <xsl:with-param name='atc' select='$atc'/>
        </xsl:apply-templates>
      </xsl:when>
      <xsl:otherwise>
        <xsl:message>unable to find tpp-reference "<xsl:value-of select='substring-after(@xlink:href, "#")'/>" for item "<xsl:value-of select='ancestor::pbs:prescribing-rule/pbs:code'/>"</xsl:message>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

  <xsl:template match='pbs:tpp'>
    <xsl:param name='pr' select='/..'/>
    <xsl:param name='pricing' select='/..'/>
    <xsl:param name='tpp-ref' select='/..'/>
    <xsl:param name='atc' select='/..'/>

    <xsl:choose>
      <xsl:when test='not($pr)'>
        <xsl:message>no prescribing rule when processing TPP "<xsl:value-of select='@xml:id'/>"</xsl:message>
      </xsl:when>
      <xsl:when test='not($pricing)'>
        <xsl:message>no pricing node when processing TPP "<xsl:value-of select='@xml:id'/>"</xsl:message>
      </xsl:when>

      <xsl:otherwise>
        <xsl:apply-templates select='$atc'>
          <xsl:with-param name='pr' select='$pr'/>
          <xsl:with-param name='pricing' select='$pricing'/>
          <xsl:with-param name='tpp' select='.'/>
          <xsl:with-param name='tpp-ref' select='$tpp-ref'/>
        </xsl:apply-templates>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

  <xsl:template match='pbs:ATC'>
    <xsl:param name='pr' select='/..'/>
    <xsl:param name='pricing' select='/..'/>
    <xsl:param name='tpp' select='/..'/>
    <xsl:param name='tpp-ref' select='/..'/>

    <xsl:variable name='drug-type'
      select='$pr/ancestor::pbs:listings-list[1]/pbs:info/pbs:code'/>

    <xsl:variable name='dr.this'>
      <xsl:call-template name="get-default-dispensing-rule">
        <xsl:with-param name="qnames" select="$qnames"/>
        <xsl:with-param name="program" select="$drug-type"/>
      </xsl:call-template>
    </xsl:variable>
    <xsl:variable name='groups.pr'
      select='key("group", $pr/pbs:member-of-list/pbs:member-of/@xlink:href)'/>

    <xsl:choose>
      <xsl:when test='not($pr)'>
        <xsl:message>no prescribing rule when processing ATC "<xsl:value-of select='.'/>"</xsl:message>
      </xsl:when>
      <xsl:when test='not($pricing)'>
        <xsl:message>no pricing data when processing ATC "<xsl:value-of select='.'/>"</xsl:message>
      </xsl:when>
      <xsl:when test='not($tpp)'>
        <xsl:message>no TPP when processing ATC "<xsl:value-of select='.'/>"</xsl:message>
      </xsl:when>

      <xsl:otherwise>
        <!-- Drug type code -->
        <xsl:choose>
            <xsl:when test='$groups.pr[pbs:type = "group:special-patient-exemption"]'>
            <xsl:choose>
              <xsl:when test='$drug-type = "IN" or
                              $drug-type = "IP"'>
                <xsl:value-of select='$drug-type'/>
              </xsl:when>
              <xsl:when test='$drug-type = "CT"'>CS</xsl:when>
              <xsl:when test='$drug-type = "GE" and
                              $groups.pr[pbs:name = "http://schema.pbs.gov.au/Group#dental" or pbs:name = "group:dental"] and
                              not($groups.pr[pbs:name = "http://schema.pbs.gov.au/Group#medical" or pbs:name = "group:medical"])'>DS</xsl:when>
              <xsl:when test='$drug-type = "GE"'>SB</xsl:when>
              <xsl:otherwise>
                <xsl:value-of select='$drug-type'/>
                <xsl:message>Unable to determine special benefits drug type for "<xsl:value-of select='$drug-type'/>" - item <xsl:value-of select='$pr/pbs:code'/></xsl:message>
              </xsl:otherwise>
            </xsl:choose>
          </xsl:when>
          <xsl:otherwise>
            <xsl:value-of select='$drug-type'/>
          </xsl:otherwise>
        </xsl:choose>
        <xsl:value-of select='$delimiter'/>
        <!-- ATC -->
        <xsl:value-of select='substring-after(., ":")'/>
        <xsl:value-of select='$delimiter'/>
        <!-- ATC type -->
        <!-- It is a secondary ATC type if there is another ATC code listed before this one -->
        <xsl:choose>
          <xsl:when test="preceding-sibling::pbs:ATC">
            <xsl:text>S</xsl:text>
          </xsl:when>
          <xsl:otherwise>
            <xsl:text>P</xsl:text>
          </xsl:otherwise>
        </xsl:choose>
        <xsl:value-of select='$delimiter'/>
        <!-- ATC print option -->
        <xsl:text>1</xsl:text>
        <xsl:value-of select='$delimiter'/>
        <!-- PBS code -->
        <xsl:value-of select='$pr/pbs:code'/>
        <xsl:value-of select='$delimiter'/>
        <!-- Restriction flag -->
        <xsl:choose>
          <xsl:when test='$pr/@type = "unrestricted"'>U</xsl:when>
          <xsl:when test='$pr/@type = "restricted"'>R</xsl:when>
          <xsl:otherwise>A</xsl:otherwise>
        </xsl:choose>
        <xsl:value-of select='$delimiter'/>
        <!-- Caution flag -->
        <xsl:variable name='cautions'>
          <xsl:apply-templates
            select='$pr/*/rwt:restriction-references-list/rwt:restriction-reference'
            mode='caution'/>
        </xsl:variable>
        <xsl:if test='$cautions != ""'>C</xsl:if>
        <xsl:value-of select='$delimiter'/>
        <!-- Note flag -->
        <xsl:variable name='notes'>
          <xsl:apply-templates
            select='$pr/*/rwt:restriction-references-list/rwt:restriction-reference'
            mode='note'/>
        </xsl:variable>
        <xsl:if test='$notes != ""'>N</xsl:if>
        <xsl:value-of select='$delimiter'/>
        <!-- Maximum Quantity -->
        <xsl:choose>
          <xsl:when test='$pr/pbs:infusible'>
            <xsl:value-of select='$pr/pbs:infusible/pbs:maximum-quantity[@reference = "unit-of-measure"]'/>
          </xsl:when>
          <xsl:when test='$pr/pbs:ready-prepared/pbs:maximum-quantity[@reference = "pack"] and
                          $pr/pbs:ready-prepared/pbs:maximum-quantity[@reference = "unit-of-use"]'>
            <xsl:value-of select='$pr/pbs:ready-prepared/pbs:maximum-quantity[@reference = "unit-of-use"]'/>
          </xsl:when>
          <xsl:otherwise>
            <xsl:value-of select='$pr/pbs:ready-prepared/pbs:maximum-quantity'/>
          </xsl:otherwise>
        </xsl:choose>
        <xsl:value-of select='$delimiter'/>
        <!-- Number of repeats -->
        <xsl:value-of select='$pr/*/pbs:number-repeats'/>
        <xsl:value-of select='$delimiter'/>
        <!-- Manufacturer's code -->
        <xsl:value-of select='key("organisation", $tpp/pbs:organisation-reference/@xlink:href)/pbs:code'/>
        <xsl:value-of select='$delimiter'/>
        <!-- Pack size -->
        <xsl:choose>
          <xsl:when test='$tpp/pbs:pack-size'>
            <xsl:value-of select='$tpp/pbs:pack-size'/>
          </xsl:when>
          <xsl:when test='$tpp/../pbs:pack-size'>
            <xsl:value-of select='$tpp/../pbs:pack-size'/> <!-- MPP -->
          </xsl:when>
        </xsl:choose>
        <xsl:value-of select='$delimiter'/>
        <!-- Markup code -->
        <xsl:variable name='markupCode'>
          <xsl:choose>
            <xsl:when test='$pr/pbs:infusible'>
              <xsl:value-of select='key("markup-band", $pricing/pbs:tpp-list[1]/pbs:tpuu-pharmacy-price/pbs:price[@dispensing-rule = $dr.this]/pbs:markup/@xlink:href)/pbs:code'/>
            </xsl:when>
            <xsl:otherwise>
              <xsl:value-of select='key("markup-band", $pricing/pbs:pack-price/pbs:price[@dispensing-rule = $dr.this]/pbs:markup/@xlink:href)/pbs:code'/>
            </xsl:otherwise>
          </xsl:choose>
        </xsl:variable>
        <xsl:choose>
          <xsl:when test="$testing-mode = true() and $markupCode = ''">
            <xsl:text>A</xsl:text>
          </xsl:when>
          <xsl:otherwise>
            <xsl:value-of select="$markupCode"/>
          </xsl:otherwise>
        </xsl:choose>
        <xsl:value-of select='$delimiter'/>
        <!-- Dispensing fee code -->
        <xsl:variable name='fees'
          select='key("fee-definition", $pricing/pbs:dpmq/pbs:price[@dispensing-rule = $dr.this]/pbs:fee/@xlink:href)'/>
        <xsl:choose>
          <xsl:when test='$pr/pbs:infusible and
                          ($drug-type = "IP" or
                          $drug-type = "TZ")'>NF</xsl:when>
          <xsl:when test='$pr/pbs:infusible'>RP</xsl:when>
          <xsl:when test='$fees[pbs:type = "fee:none"]'>NF</xsl:when>
          <xsl:when test='$fees[pbs:type = "fee:dispensing"] and
                          $fees[pbs:type = "fee:extemp"] and
                          $fees[pbs:type = "fee:water-added"]'>EW</xsl:when>
          <xsl:when test='$fees[pbs:type = "fee:dispensing"] and
                          $fees[pbs:type = "fee:extemp"]'>EP</xsl:when>
          <xsl:when test='$fees[pbs:type = "fee:dispensing"]'>RP</xsl:when>
          <xsl:when test='$fees'>
            <xsl:text>XX</xsl:text>
            <xsl:message>Found fee "<xsl:value-of select='$fees/pbs:type'/>", but unknown type of fee for item <xsl:value-of select='$pr/pbs:code'/> in program <xsl:value-of select='$pr/ancestor::pbs:listings-list/pbs:info/pbs:code'/></xsl:message>
          </xsl:when>
          <xsl:otherwise>
            <xsl:text>XX</xsl:text>
            <xsl:message>Unable to determine fee code for item <xsl:value-of select='$pr/pbs:code'/> in program <xsl:value-of select='$pr/ancestor::pbs:listings-list/pbs:info/pbs:code'/> with dispensing rule <xsl:value-of select='$dr.this'/></xsl:message>
          </xsl:otherwise>
        </xsl:choose>
        <xsl:value-of select='$delimiter'/>
        <!-- Dangerous drug code -->
        <xsl:if test='($tpp/pbs:member-of-list/pbs:member-of[key("group", @xlink:href)/pbs:type = "group:dangerous-drug"] |
                      $tpp/../pbs:member-of-list/pbs:member-of[key("group", @xlink:href)/pbs:type = "group:dangerous-drug"]) and
                      $pr/ancestor::pbs:listings-list/pbs:dispensing-rules-list/pbs:dispensing-rule[@about = $dr.this]/pbs:fees-list/pbs:fee-definition[pbs:type = "fee:dangerous-drug"]'>DD</xsl:if>
        <xsl:value-of select='$delimiter'/>
        <!-- Brand premium -->
        <xsl:choose>
          <xsl:when test='$pricing/pbs:dpmq/pbs:price[@dispensing-rule = $dr.this]/pbs:contribution[pbs:type = "contrib:brand-premium"]'>
            <xsl:value-of select='$pricing/pbs:dpmq/pbs:price[@dispensing-rule = $dr.this]/pbs:contribution[pbs:type = "contrib:brand-premium"]/pbs:amount'/>
          </xsl:when>
          <xsl:otherwise>0.00</xsl:otherwise>
        </xsl:choose>
        <xsl:value-of select='$delimiter'/>
        <!-- Therapeutic Group Premium -->
        <xsl:choose>
          <xsl:when test='$pr/pbs:infusible'>
            <xsl:choose>
              <xsl:when test='$pr/pbs:infusible/pbs:pricing/pbs:manufacturer/pbs:dpmq/pbs:price[@dispensing-rule = $dr.this]/pbs:contribution[pbs:type = "contrib:therapeutic-group" or
                              pbs:type = "contrib:special-patient"]'>
                <xsl:value-of select='$pr/pbs:infusible/pbs:pricing/pbs:manufacturer/pbs:dpmq/pbs:price[@dispensing-rule = $dr.this]/pbs:contribution[pbs:type = "contrib:therapeutic-group" or
                              pbs:type = "contrib:special-patient"]/pbs:amount'/>
              </xsl:when>
              <xsl:otherwise>0.00</xsl:otherwise>
            </xsl:choose>
          </xsl:when>
          <xsl:when test='$pricing/pbs:dpmq/pbs:price[@dispensing-rule = $dr.this]/pbs:contribution[pbs:type = "contrib:therapeutic-group" or
                          pbs:type = "contrib:special-patient"]'>
            <xsl:value-of select='$pricing/pbs:dpmq/pbs:price[@dispensing-rule = $dr.this]/pbs:contribution[pbs:type = "contrib:therapeutic-group" or
                                  pbs:type = "contrib:special-patient"]/pbs:amount'/>
          </xsl:when>
          <xsl:otherwise>0.00</xsl:otherwise>
        </xsl:choose>
        <xsl:value-of select='$delimiter'/>
        <!-- Commonwealth Price to Pharmacist -->
        <xsl:variable name='p2p.cwlth'>
          <xsl:choose>
            <xsl:when test='$pr/pbs:infusible'>
              <!-- P2P = EMP because infusibles do not have wholesale markup -->
              <xsl:value-of select='$tpp-ref/../pbs:tpuu-ex-manufacturer'/>
            </xsl:when>
            <xsl:when test='$pricing/../pbs:reimbursement/pbs:to-pharmacist/pbs:price[@dispensing-rule = $dr.this]'>
              <xsl:value-of select='$pricing/../pbs:reimbursement/pbs:to-pharmacist/pbs:price[@dispensing-rule = $dr.this]/pbs:amount'/>
            </xsl:when>
            <xsl:when test='$pricing/pbs:to-pharmacist/pbs:price[@dispensing-rule = $dr.this]'>
              <!-- TODO: further check that this is a ready-prepared,no-premium[,no-charge] pricing model -->
              <xsl:value-of select='$pricing/pbs:to-pharmacist/pbs:price[@dispensing-rule = $dr.this]/pbs:amount'/>
            </xsl:when>
            <xsl:otherwise>0.00</xsl:otherwise>
          </xsl:choose>
        </xsl:variable>
        <xsl:value-of select='$p2p.cwlth'/>
        <xsl:value-of select='$delimiter'/>
        <!-- Commonwealth DPMQ -->
        <xsl:variable name='dpmq.cwlth'>
          <xsl:choose>
            <xsl:when test='$pr/pbs:infusible'>
              <xsl:choose>
                <xsl:when test='$pricing/../pbs:dpmq/pbs:price[@dispensing-rule = $dr.this]'>
                  <xsl:value-of select='$pricing/../pbs:dpmq/pbs:price[@dispensing-rule = $dr.this]/pbs:amount'/>
                </xsl:when>
                <xsl:otherwise>0.00</xsl:otherwise>
              </xsl:choose>
            </xsl:when>
            <xsl:when test='$pricing/../pbs:reimbursement/pbs:dpmq/pbs:price[@dispensing-rule = $dr.this]'>
              <xsl:value-of select='$pricing/../pbs:reimbursement/pbs:dpmq/pbs:price[@dispensing-rule = $dr.this]/pbs:amount'/>
            </xsl:when>
            <xsl:when test='$pricing/pbs:dpmq/pbs:price[@dispensing-rule = $dr.this]'>
              <!-- TODO: further check that this is a ready-prepared,no-premium[,no-charge] pricing model -->
              <xsl:value-of select='$pricing/pbs:dpmq/pbs:price[@dispensing-rule = $dr.this]/pbs:amount'/>
            </xsl:when>
            <xsl:otherwise>0.00</xsl:otherwise>
          </xsl:choose>
        </xsl:variable>
        <xsl:value-of select='$dpmq.cwlth'/>
        <xsl:value-of select='$delimiter'/>
        <!-- Therapeutic Group Manufacturer's Price to Pharmacist -->
        <!-- Undefined for infusible listings -->
        <xsl:variable name='p2p.lowest'>
          <xsl:choose>
            <xsl:when test='$pricing/../pbs:lowest/pbs:to-pharmacist/pbs:price[@dispensing-rule = $dr.this]'>
              <xsl:value-of select='$pricing/../pbs:lowest/pbs:to-pharmacist/pbs:price[@dispensing-rule = $dr.this]/pbs:amount'/>
            </xsl:when>
            <xsl:otherwise>0.00</xsl:otherwise>
          </xsl:choose>
        </xsl:variable>
        <xsl:choose>
          <xsl:when test='$p2p.lowest != $p2p.cwlth'>
            <xsl:value-of select='$p2p.lowest'/>
          </xsl:when>
          <xsl:otherwise>0.00</xsl:otherwise>
        </xsl:choose>
        <xsl:value-of select='$delimiter'/>
        <!-- Therapeutic Group Manufacturer's DPMQ -->
        <xsl:variable name='dpmq.lowest'>
          <xsl:choose>
            <xsl:when test="$pricing/../pbs:lowest">
              <xsl:value-of select="$pricing/../pbs:lowest/pbs:dpmq/pbs:price[@dispensing-rule = $dr.this]/pbs:amount"/>
            </xsl:when>
            <xsl:otherwise>0.00</xsl:otherwise>
          </xsl:choose>
        </xsl:variable>
        <xsl:choose>
          <xsl:when test='$dpmq.lowest != $dpmq.cwlth'>
            <xsl:value-of select='$dpmq.lowest'/>
          </xsl:when>
          <xsl:otherwise>0.00</xsl:otherwise>
        </xsl:choose>
        <xsl:value-of select='$delimiter'/>
        <!-- Manufacturer's Price to Pharmacist -->
        <xsl:choose>
          <xsl:when test='$pr/pbs:infusible'>
            <!-- P2P = EMP for infusible listings -->
            <xsl:choose>
              <xsl:when test="$tpp/pbs:tpuu/pbs:ex-manufacturer">
                <xsl:value-of select="$tpp/pbs:tpuu/pbs:ex-manufacturer"/>
              </xsl:when>
              <xsl:when test='$tpp/pbs:tpuu-ex-manufacturer'>
                <xsl:value-of select='$tpp/pbs:tpuu-ex-manufacturer'/>
              </xsl:when>
              <xsl:otherwise>0.00</xsl:otherwise>
            </xsl:choose>
          </xsl:when>
          <xsl:when test='$pricing/pbs:to-pharmacist/pbs:price[@dispensing-rule = $dr.this] and
                          $pricing/pbs:to-pharmacist/pbs:price[@dispensing-rule = $dr.this]/pbs:amount = $p2p.lowest'>
            <xsl:text>0.00</xsl:text>
          </xsl:when>
          <xsl:when test='$pricing/pbs:to-pharmacist/pbs:price[@dispensing-rule = $dr.this] and
                          $pricing/pbs:to-pharmacist/pbs:price[@dispensing-rule = $dr.this]/pbs:amount = $p2p.cwlth'>
            <xsl:text>0.00</xsl:text>
          </xsl:when>
          <xsl:when test='$pricing/pbs:to-pharmacist/pbs:price[@dispensing-rule = $dr.this]'>
            <xsl:value-of select='$pricing/pbs:to-pharmacist/pbs:price[@dispensing-rule = $dr.this]/pbs:amount'/>
          </xsl:when>
          <xsl:otherwise>0.00</xsl:otherwise>
        </xsl:choose>
        <xsl:value-of select='$delimiter'/>
        <!-- Manufacturer's DPMQ -->
        <xsl:choose>
          <xsl:when test='$pr/pbs:infusible and
                          $pr/pbs:infusible/pbs:pricing/pbs:manufacturer/pbs:dpmq/pbs:price[@dispensing-rule = $dr.this]/pbs:amount != $dpmq.cwlth'>
            <xsl:value-of select='$pr/pbs:infusible/pbs:pricing/pbs:manufacturer/pbs:dpmq/pbs:price[@dispensing-rule = $dr.this]/pbs:amount'/>
          </xsl:when>
          <xsl:when test='$pr/pbs:infusible'>
            <xsl:text>0.00</xsl:text>
          </xsl:when>
          <xsl:when test='$pricing/pbs:dpmq/pbs:price[@dispensing-rule = $dr.this] and
                          $pricing/pbs:dpmq/pbs:price[@dispensing-rule = $dr.this]/pbs:amount = $dpmq.lowest'>
            <xsl:text>0.00</xsl:text>
          </xsl:when>
          <xsl:when test='$pricing/pbs:dpmq/pbs:price[@dispensing-rule = $dr.this] and
                          $pricing/pbs:dpmq/pbs:price[@dispensing-rule = $dr.this]/pbs:amount = $dpmq.cwlth'>
            <xsl:text>0.00</xsl:text>
          </xsl:when>
          <xsl:when test='$pricing/pbs:dpmq/pbs:price[@dispensing-rule = $dr.this]'>
            <xsl:value-of select='$pricing/pbs:dpmq/pbs:price[@dispensing-rule = $dr.this]/pbs:amount'/>
          </xsl:when>
          <xsl:otherwise>0.00</xsl:otherwise>
        </xsl:choose>
        <xsl:value-of select='$delimiter'/>
        <!-- Maximum Recordable Value for Safety Net -->
        <xsl:choose>
          <xsl:when test='$pr/pbs:infusible'>
            <xsl:value-of select='$pr/pbs:infusible/pbs:pricing/pbs:maximum-safety-net-value/pbs:price[@dispensing-rule = $dr.this]/pbs:amount'/>
          </xsl:when>
          <xsl:when test='$pricing/pbs:maximum-safety-net-value/pbs:price[@dispensing-rule = $dr.this]'>
            <xsl:value-of select='$pricing/pbs:maximum-safety-net-value/pbs:price[@dispensing-rule = $dr.this]/pbs:amount'/>
          </xsl:when>
          <xsl:when test='$pricing/../pbs:maximum-safety-net-value/pbs:price[@dispensing-rule = $dr.this]'>
            <xsl:value-of select='$pricing/../pbs:maximum-safety-net-value/pbs:price[@dispensing-rule = $dr.this]/pbs:amount'/>
          </xsl:when>
          <xsl:otherwise>0.00</xsl:otherwise>
        </xsl:choose>
        <xsl:value-of select='$delimiter'/>
        <!-- Bioequivalence flag -->
        <xsl:variable name="bslg.pr" select="$groups.pr[pbs:type = 'group:brand-substitutable']"/>
        <xsl:choose>
          <xsl:when test="count($bslg.pr) = 0"/>
          <!-- if PR is not in any BSLG then no listed products are substitutable -->
          <xsl:when test="count($bslg.pr) = 1">
            <!-- If listed product is in this group and there are 2 or more members
                 then automatically get 'a', otherwise blank.
              -->
            <xsl:if test="$tpp/pbs:member-of-list[pbs:member-of/@xlink:href = concat('#', $bslg.pr/@xml:id)] and
              count(key('members', concat('#', $bslg.pr/@xml:id))/../../self::pbs:tpp[not(ancestor::pbs:previous)]) > 1">
              <xsl:text>a</xsl:text>
            </xsl:if>
          </xsl:when>
          <xsl:otherwise>
              
            <!-- There are multiple BSLGs so there will be 'a', 'b', etc.
                 Find the group that this TPP is also a member of,
                 make sure there are 2 more TPP members,
                 then find its position in the (sorted) list of BSLGs.
              -->

            <xsl:variable name="bslg.tpp"
              select='key("group", $tpp/pbs:member-of-list/pbs:member-of/@xlink:href)[pbs:type = "group:brand-substitutable"]'/>

            <!-- Find the intersection between the tpp and pr groups -->
            <xsl:variable name='bslg.both.id'>
              <xsl:for-each select="$bslg.pr">
                <xsl:sort select="pbs:name"/> <!-- sorting makes the indicator stable -->
                <xsl:if test="$bslg.tpp[@xml:id = current()/@xml:id] and
                  count(key('members', concat('#', @xml:id))/../../self::pbs:tpp[not(ancestor::pbs:previous)]) > 1">
                  <xsl:value-of select="position()"/>
                  <xsl:text> </xsl:text>
                </xsl:if>
              </xsl:for-each>
            </xsl:variable>

            <!-- XPath 2.0 could automatically convert to a character,
                 but it would be extremely unlikely to need to go past 'd'.
              -->
            <xsl:choose>
              <xsl:when test="normalize-space($bslg.both.id) = ''"/>
              <xsl:when test="$bslg.both.id = 1">a</xsl:when>
              <xsl:when test="$bslg.both.id = 2">b</xsl:when>
              <xsl:when test="$bslg.both.id = 3">c</xsl:when>
              <xsl:when test="$bslg.both.id = 4">d</xsl:when>
              <xsl:otherwise>e</xsl:otherwise>
            </xsl:choose>
            
          </xsl:otherwise>
        </xsl:choose>
        <xsl:value-of select='$delimiter'/>
        <!-- Brand name -->
        <xsl:apply-templates select='$tpp/db:subtitle'/>
        <xsl:value-of select='$delimiter'/>
        <!-- Drug name -->
        <xsl:apply-templates select='$tpp/../../db:title' mode='drug-name'/>
        <xsl:value-of select='$delimiter'/>
        <!-- Form and Strength -->
        <xsl:call-template name='find-form-strength'>
          <xsl:with-param name='pr' select='$pr'/>
          <xsl:with-param name='tpp' select='$tpp'/>
        </xsl:call-template>
        <xsl:text>&#xa;</xsl:text>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

  <xsl:template name='find-form-strength'>
    <xsl:param name='pr' select='/..'/>
    <xsl:param name='tpp' select='/..'/>

    <xsl:choose>
      <xsl:when test='$pr/pbs:infusible'>
        <xsl:apply-templates select='$tpp/pbs:preferred-term' mode="textonly"/>
      </xsl:when>
      <xsl:otherwise>
        <xsl:apply-templates select='$tpp/../db:title'/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

  <xsl:template match='rwt:restriction-reference' mode='caution'>
    <xsl:apply-templates select='key("restrictions", @xlink:href)' mode='caution'/>
  </xsl:template>
  <xsl:template match='rwt:restriction' mode='caution'>
    <xsl:apply-templates select='rwt:circumstance |
                                 key("restrictions", rwt:caution-reference/@xlink:href)'
      mode='caution'/>
  </xsl:template>
  <xsl:template match='rwt:circumstance' mode='caution'>
    <xsl:apply-templates select='rwt:caution |
                                 key("restrictions", rwt:caution-reference/@xlink:href)'
      mode='caution'/>
  </xsl:template>
  <xsl:template match='rwt:caution' mode='caution'>
    <xsl:value-of select='pbs:code'/>
  </xsl:template>
  <xsl:template match='rwt:administrative-advice' mode='caution'/>

  <xsl:template match='rwt:restriction-reference' mode='note'>
    <xsl:apply-templates select='key("restrictions", @xlink:href)' mode='note'/>
  </xsl:template>
  <xsl:template match='rwt:restriction' mode='note'>
    <xsl:apply-templates select='rwt:circumstance |
                                 key("restrictions", rwt:circumstance-reference/@xlink:href) | 
                                 key("restrictions", rwt:administrative-advice-reference/@xlink:href) | 
                                 key("restrictions", rwt:definition-reference/@xlink:href)'
      mode='note'/>
  </xsl:template>
  <xsl:template match='rwt:circumstance' mode='note'>
    <xsl:apply-templates select='rwt:administrative-advice |
                                 key("restrictions", rwt:administrative-advice-reference/@xlink:href)'
      mode='note'/>
  </xsl:template>
  <xsl:template match='rwt:administrative-advice |
                       rwt:definition'
    mode='note'>
    <!-- Exclude notes with non-numeric codes (cto and scm) -->
    <xsl:if test="string(number(pbs:code)) != 'NaN'">
      <xsl:value-of select='pbs:code'/>
    </xsl:if>
  </xsl:template>

  <xsl:template name='get-fee-code'>
    <xsl:param name='fee' select='/..'/>

    <xsl:call-template name='fee-to-text'>
      <xsl:with-param name='uri' select='$fee/pbs:type'/>
    </xsl:call-template>
  </xsl:template>

  <xsl:template match='db:title' mode='drug-name'>
    <xsl:apply-templates>
      <xsl:with-param name='limit'>80</xsl:with-param>
    </xsl:apply-templates>
  </xsl:template>
  <xsl:template match='pbs:label|db:title|pbs:preferred-term'>
    <xsl:apply-templates>
      <xsl:with-param name='limit'>150</xsl:with-param>
    </xsl:apply-templates>
  </xsl:template>
  <xsl:template match='db:subtitle'>
    <xsl:apply-templates>
      <xsl:with-param name='limit'>45</xsl:with-param>
    </xsl:apply-templates>
  </xsl:template>

  <xsl:template match='db:superscript|db:subscript'>
    <xsl:text> </xsl:text>
    <xsl:apply-templates/>
  </xsl:template>

  <xsl:template match='text()'>
    <xsl:param name='limit'/>

    <xsl:variable name='text'>
      <xsl:call-template name="ascii">
	<xsl:with-param name="text" select="."/>
      </xsl:call-template>
    </xsl:variable>

    <xsl:choose>
      <xsl:when test='$truncate = true() and $limit != ""'>
        <xsl:value-of select='substring($text, 1, $limit)'/>
      </xsl:when>
      <xsl:otherwise>
        <xsl:value-of select='$text'/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

  <xsl:template match='*'/>
  
</xsl:stylesheet>

